﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.ServiceModel;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DeSleeper.Library;
using DeSleeper.WebClient.WakeOnLanProxy;

namespace DeSleeper.WebClient
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnWake_Click(object sender, EventArgs e)
        {
            var identity = HttpContext.Current.User.Identity as WindowsIdentity;
            if (identity == null || identity.IsAnonymous)
                throw new HttpException(403, "Forbidden");

            using (var context = identity.Impersonate())
            {
                if (WakeOnLanHelper.ValidateMacAddress(macAddress.Text))
                {
                    var client = new WakeUpServiceClient();
                	client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Delegation;
                    client.WakeUp(macAddress.Text);
                }
                else
                {
                    ErrorValue.InnerText =
                        "Invalid MAC Address.  A MAC Address is a sequence of 6 hexadecimal pairs. Example: AB-CD-EF-01-23-45";
                }
                context.Undo();
            }
        }

        protected override void OnError(EventArgs e)
        {
            if (Context.Server.GetLastError().Message == "Anonymous usage is not allowed.")
            {
                Response.StatusCode = 403;
                Response.End();
            }
            else
            {
                base.OnError(e);
            }
            
        }
    }
}
